# -*- coding: utf-8 -*-
# !/usr/bin/env python
import os
import cv2
import colorList


def show_color(filename):
    frame = cv2.imread(filename)

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    max_sum = -100
    color = None
    color_dict = colorList.getColorList()
    for d in color_dict:
        mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1])
        cv2.imwrite(d + '.jpg', mask)
        binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)[1]
        binary = cv2.dilate(binary, None, iterations=2)
        contours, hierarchy = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        sum = 0
        for c in contours:
            sum += cv2.contourArea(c)
        if sum > max_sum:
            max_sum = sum
            color = d
        os.remove(d + '.jpg')
    return color


for filename in ['123.jpg', '图片1.jpg', '图片2.jpg', '图片3.jpg', '图片4.jpg', '图片5.jpg']:
    print(filename)
    color = show_color("./图片颜色鉴定/" + filename)
    print(color)
